/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.commons.web.jsf.utils;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * @author Jorge E. Villaverde
 * @version 0.0.1
 * @since 0.0.1	
 */
public abstract class ResourceBundleUtil {
	private static final String MESSAGE_BUNDLE = "MessageResources";
	private static final String VALIDATION_MSG = "ValidationMessages";

	private static ResourceBundle rb;
	private static ResourceBundle vm;

	static{
		try {
			rb =  ResourceBundle.getBundle(MESSAGE_BUNDLE);
			vm =  ResourceBundle.getBundle(VALIDATION_MSG);
		} catch (Exception e) {
		}
	}
	
	
	public static String getResourceBundleString(String key){
		if(rb == null)
			return "";
		try {
			return rb.getString(key);
		} catch (java.util.MissingResourceException e) {
			return "ERROR: " + key + " NOT FOUND";
		}		
	}

	public static String getResourceBundleString(String key, Locale locale){
		String bundleName = MESSAGE_BUNDLE + "_" + locale.getLanguage();
		ResourceBundle rb =  ResourceBundle.getBundle(bundleName);
		try {
			return rb.getString(key);
		} catch (java.util.MissingResourceException e) {
			// si no lo encontramos en el bundle del locale, probamos en el por defecto
			return getResourceBundleString(key);
		}
	}

	public static String getValidationMessageString(String key){
		if(vm == null)
			return "";
		return vm.getString(key);
	}
	
	public static String getValidationMessageString(String key, Locale locale){
		String bundleName = VALIDATION_MSG + "_" + locale.getLanguage();
		ResourceBundle rb =  ResourceBundle.getBundle(bundleName);
		try {
			return rb.getString(key);
		} catch (java.util.MissingResourceException e) {
			// si no lo encontramos en el bundle del locale, probamos en el por defecto
			return getValidationMessageString(key);
		}		
	}
	
	public static String getFormatedResourceBundleString(String key, Object... args){
		String formatMessage = getResourceBundleString(key);
		return MessageFormat.format(formatMessage, args);		
	}

	public static String getFormatedResourceBundleString(String key, Locale locale, Object... args){
		String formatMessage = getResourceBundleString(key, locale);
		return MessageFormat.format(formatMessage, args);		
	}	
}
